import * as CustomerApi from '@src/api/CustomerApi.ts';

import {
  FormFieldMap,
  SettingComponents
} from '@src/component/form/components';
import * as Utils from '@src/component/form/util';

import SearchProductSelect from './components/SearchProductSelect.vue';
import SearchStatusSelect from './components/SearchStatusSelect.vue';
import SearchCustomerSelect from './components/SearchCustomerSelect.vue';
import SearchAddressSelect from './components/SearchAddressSelect.vue';

export default {
  name: 'base-search-item',
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    form: {
      type: Object,
      default: () => ({})
    }
  },
  methods: {
    searchAddress(params, customer) {
      const pms = params || {};
      pms.customerId = this.form.customer || '';
      return CustomerApi.getTaskCustomerAddress(pms)
        .then(res => {
          if (!res || !res.list) return;

          res.list = res.list.map(custoner =>
            Object.freeze({
              label: custoner.name,
              value: custoner.id,
              ...custoner
            })
          );
          return res;
        })
        .catch(e => console.error(e));
    },
    searchCustomer(params) {
      const pms = params || {};

      return CustomerApi.getCustomerListAsyn(pms)
        .then(res => {
          if (!res || !res.list) return;

          res.list = res.list.map(custoner =>
            Object.freeze({
              label: custoner.name,
              value: custoner.id,
              ...custoner
            })
          );
          return res;
        })
        .catch(e => console.error(e));
    },
    searchProduct(params) {
      const pms = params || {};

      pms.customerId = this.form.customer || '';
      return CustomerApi.getTaskCustomerProduct(pms)
        .then(res => {
          if (!res || !res.list) return;
          res.list = res.list.map(product =>
            Object.freeze({
              label: product.name,
              value: product.id,
              ...product
            })
          );
          return res;
        })
        .catch(e => console.error(e));
    },
    /**
     * 更新搜索表单的值
     * @param {*} event
     * @param {*} action
     */
    update(event, action) {
      if (action === 'tags') {
        return this.$emit('update', { key: 'tags', value: event });
      }

      if (action === 'dist') {
        return this.$emit('update', { key: 'area', value: event });
      }

      const f = event.field;

      this.$emit('update', {
        key: f.fieldName,
        value: event.newValue
      });
    },
    /**
     * 渲染表单各个搜索组件
     * @param {*} h
     * @param {*} field
     */
    renderSearchComp(h, field) {
      const f = {
        ...Object.freeze(field)
      };

      if (f.formType === 'datetime' || f.formType === 'planTime') {
        f.formType = 'date';
      }

      if (f.formType === 'serialNumber') {
        f.formType = 'text';
      }


      let comp = FormFieldMap.get(f.formType);

      if (
        !comp &&
        f.formType !== 'tags' &&
        f.formType !== 'area' &&
        f.formType !== 'linkman'
      ) {
        return null;
      }

      if (f.formType === 'select') {
        // 下拉框
        f.setting.isMulti = false;
      }

      let childComp = null;

      if (f.formType === 'tags') {
        // 选择团队

        childComp = h('biz-team-select', {
          props: {
            value: this.form[f.fieldName] || []
          },
          on: {
            input: event => this.update(event, 'tags')
          }
        });
      } else if (f.fieldName === 'status') {
        //数据状态;
        childComp = h('search-status-select', {
          props: {
            multiple: true,
            field: f,
            value: this.form[f.fieldName],
            disableMap: true
          },
          on: {
            input: event => {
              this.$set(this.form, f.fieldName, event);
            }
          }
        });
      } else if (f.formType == 'customer') {
        // 客户
        let value = this.form[f.fieldName];
        childComp = h('search-customer-select', {
          props: {
            placeholder: this.$t('common.placeholder.selectCustomer'),
            field: f,
            value: value ? [{ label: this.customer.name || '', value }] : [],
            remoteMethod: this.searchCustomer
          },
          on: {
            input: event => {
              this.customer = event && event.length > 0 ? event[0] : {};
              this.$set(this.form, f.fieldName, this.customer.id);
            }
          }
        });
      }
      // 废弃 使用单行文本模糊搜索产品名称
      else if (f.formType == 'product') {
        //   //产品
        //   let value = this.form[f.fieldName];
        let value = this.form[f.fieldName];
        childComp = h('form-text', {
          props: {
            placeholder: this.$t('common.validate.inputProductName'),
            field: f,
            value: this.form[f.fieldName],
          },
          on: {
            update: event => this.update(event)
          }
        });
      }
      else if (f.formType === 'user') {
        // 人员
        childComp = h('user-search', {
          props: {
            multiple: true,
            field: f,
            value: this.form[f.fieldName],
            disableMap: true
          },
          on: {
            update: event => this.update(event)
          }
        });
      } else if (f.formType === 'area') {
        // 区域
        childComp = h('base-dist', {
          props: {
            value: this.form[f.fieldName],
            showDefaultCountry: false
          },
          on: {
            input: event => this.update(event, 'dist')
          }
        });
      } else if (f.formType === 'linkman' || f.fieldName === 'tlmName') {
        // 联系人
        f.clearable = true;
        childComp = h('linkman-search', {
          props: {
            field: f,
            value: this.form[f.fieldName],
            disableMap: true
          },
          on: {
            update: event => this.update(event)
          }
        });
      } else {
        // 默认渲染
        childComp = h(
          comp.extend && comp.extend[`${f.formType}_search`]
            ? comp.extend[`${f.formType}_search`]
            : comp.build,
          {
            props: {
              field: f,
              value: this.form[f.fieldName],
              disableMap: true,
              placeholder: Utils.genPlaceholder(f)
            },
            on: {
              update: event => this.update(event)
            }
          }
        );
      }

      return h(
        'form-item',
        {
          props: {
            label: f.displayName,
            needValidate: false
          }
        },
        [childComp]
      );
    }
  },
  render(h) {
    return this.renderSearchComp(h, this.field);
  },
  components: {
    ...SettingComponents,
    [SearchProductSelect.name]: SearchProductSelect,
    [SearchStatusSelect.name]: SearchStatusSelect,
    [SearchCustomerSelect.name]: SearchCustomerSelect,
    [SearchAddressSelect.name] : SearchAddressSelect
  }
};
